<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="queryForm">
        <el-form-item>
          <el-input v-model="queryForm.keyword" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDepartments">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="100" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门主管" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: red">已停用</span>
          <span v-if="scope.row.state=='1'" style="color: green">已启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="150" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" min-width="150" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          style="float: right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.currentPage"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
    </el-col>
    <!--保存提交界面-->
    <el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门管理" prop="manager">
          <el-select v-model="saveForm.manager" placeholder="请选择" value-key="id" clearable>
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">开启</el-radio>
            <el-radio class="radio" :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
// import util from '../../common/js/util'
// //import NProgress from 'nprogress'
// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

export default {
  data() {
    return {
      employees: [],
      deptTree: [],
      queryForm: {
        keyword:'',
        currentPage: 1,
        pageSize: 5
      },
      pageInfo: {
        list: [],
        total: 0,
      },
      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//保存界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ]
      },
      //保存界面数据
      saveForm: {
        id:null,
        name:"",
        manager: {
          id:null,
          username:""
        },
        parent: {
          id:null,
          name:""
        },
        state:null
      }
    }
  },
  methods: {
    //查询管理员数据
    getManager() {
      this.$http.get('/employee',)
          .then(res => res.data)
          .then(res => {
            if (res.success) {
              this.employees = res.data;
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              });
            }
          })
    },
    //查询部门树
    getDeptTree() {
      this.$http.get('/department/tree')
          .then(res => res.data)
          .then(res => {
            if (res.success) {
              this.deptTree = res.data;
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              });
            }
          })
          .catch(error => {
            console.log(error)
          })
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.getDepartments();
    },
    handleCurrentChange(val) {
      this.queryForm.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      // this.listLoading = true;
      // NProgress.start();
      this.$http.post('/department/query', this.queryForm)
          .then(res => res.data)
          .then(res => {
            if (res.success) {
              this.pageInfo.list = res.data.list;
              this.pageInfo.total = res.data.total;
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              });
            }
          })
          .catch(error => {
            console.log(error)
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete('/department/' + row.id)
            .then(res => res.data)
            .then(res => {
              if (res.success) {
                this.listLoading = false;
                this.handleCurrentChange(1);
                this.$message({
                  message: "删除成功！",
                  type: 'success'
                });
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                });
              }
            })
            .catch(error => {
              console.log(error)
            })
      })
    },
    //显示新增界面
    handleAdd() {
      this.getManager();
      this.getDeptTree();
      this.saveFormVisible = true;
      this.saveForm = {
        id:null,
        name:"",
        manager: {
          id:null,
          username:""
        },
        parent: {
          id:null,
          name:""
        },
        state:null
      }
    },
    //显示修改界面
    handleEdit: function (index, row) {
      this.getManager();
      this.getDeptTree();
      this.saveForm = row;
      this.saveFormVisible = true;
      //处理部门编辑页面的上级部门回显
      let parentURL=[];
      if(row.parent!==null){
          let split=row.dirPath.split("/");
          for(let i=1;i<split.length-1;i++){
              parentURL.push(parseInt(split[i]));
          }
      }
      this.saveForm.parent = parentURL;
    },
    //部门提交
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let parent = this.saveForm.parent;
            //处理parent，如果未选部门，则parent还是对象；选过部门，无论是否删除，parent都会变为数组
            if(parent.length>=0){
              if (parent.length===0){//如果选中部门后又清除部门，parent设置为null
                this.saveForm.parent = {id:null,name:""}
              }else {
                //选中部门后未清除部门，parent设置为数组的最后一个
                this.saveForm.parent = {id:parent[parent.length-1],name:""}
              }
            }
            //NProgress.start();
            this.$http.put('/department', this.saveForm)
                .then(res => res.data)
                .then(res => {
                  if (res.success) {
                    this.saveLoading = false;
                    this.saveFormVisible = false;
                    this.handleCurrentChange(1);
                    this.$message({
                      message: "提交成功！",
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: res.message,
                      type: 'error'
                    })
                  }
                })
                .catch(error => {
                  console.log(error)
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch('/department', ids)
            .then(res => res.data)
            .then(res => {
              if (res.success) {
                this.listLoading = false;
                this.handleCurrentChange(1);
                this.$message({
                  message: "删除成功！",
                  type: 'success'
                });
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                });
              }
            })
            .catch(error => {
              console.log(error)
            })
      })
    },
  },
  mounted() {
    this.getDepartments();
  }
}
</script>

<style scoped>

</style>